# ~*~ coding: utf-8 ~*~
import json
import os
import importlib,sys
importlib.reload(sys)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print (BASE_DIR)
import django
CMDB_PATH = os.path.join(BASE_DIR, 'cmdb')
sys.path.append(CMDB_PATH)
os.environ.setdefault("DJANGO_SETTINGS_MODULE","syscmdb.settings")
django.setup()
from resources.models import NewServer,ServerUser
from devops.models import AutoReCovery,MonitorConfig
from alert.models import AlertConfig

class DbSearch():
	def __init__(self):
		pass
	def Asset(self,ip):
		s = NewServer.objects.get(ip_inner=ip)
		hostname = s.hostname
		port = s.port
		username = s.server_user.username
		password = s.server_user.password
		private_key = s.server_user.privatekey

		asset = {'hostname': hostname,'ip': ip,'port': port, 'username': username, 'password': password,
				 'private_key':private_key}
		return asset

	def SelfHealing(self):
		s = AutoReCovery.objects.all()
		return s

	def AutoStatus(self,id):
		s = AutoReCovery.objects.get(pk=int(id))
		return s.status

	def AutoAction(self,id):
		s = AutoReCovery.objects.get(pk=int(id))
		return s.action

	def McStatus(self,name):
		s = MonitorConfig.objects.get(name=name)
		return s.auto_status

	def SendAlert(self,attention):
		#get maillist
		try:
			sl = MonitorConfig.objects.get(name=attention)
			if sl.alert_type == 1:
				maillist = []
				for m in sl.ml.all():
					for g in m.gl.all():
						maillist.append(g.email)
				return (1,maillist)
			if sl.alert_type == 2:
				dingurl = sl.ml.first().dingurl
				return (2,dingurl)
		except Exception as e:
			print (e)

		return None

	def SendUser(self):
		u = AlertConfig.objects.first()
		return u.cname

	def AlertMsg(self):
		u = AlertConfig.objects.first()
		return u

	def DevStatus(self,name,auto_status):
		arc = MonitorConfig.objects.get(name=name)
		arc.auto_status = auto_status
		arc.save()

		

